package com.examples.oryarok;

import static com.examples.oryarok.Constants.TABLE_NAME;
import static android.provider.BaseColumns._ID;
import static com.examples.oryarok.Constants.DATE;
import static com.examples.oryarok.Constants.NAME;
import static com.examples.oryarok.Constants.TIME;
import static com.examples.oryarok.Constants.FROM;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

//http://www.vogella.de/articles/AndroidSQLite/article.html#todo_database
//There is example that matched my code

public class MeetDataDbAdapter {
	private Context context;
	private SQLiteDatabase database;
	private MeetDataDbHelper dbHelper;

	public MeetDataDbAdapter(Context context) {
		this.context = context;
	}

	public MeetDataDbAdapter open() throws SQLException {
		dbHelper = new MeetDataDbHelper(context);
		database = dbHelper.getWritableDatabase();
		return this;
	}

	public void close() {
		dbHelper.close();
	}


	/**
	 * Create a new meet entry If the entry is successfully created return the new
	 * rowId for that entry, otherwise return a -1 to indicate failure.
	 */
	public long createEntry(String category, String summary, String description) {
		//TODO copy from existing code
		ContentValues initialValues = createContentValues("","","");//category, summary,description);
	
		return database.insert(TABLE_NAME, null, initialValues);
	}
	/**
	 * Update the row in database by _ID
	 */
	public boolean updateDbEntry(long rowId, String date, String time, String name) {
		ContentValues updateValues = createContentValues(date, time, name);

		return database.update(TABLE_NAME, updateValues, _ID + "="
				+ rowId, null) > 0;
	}

	/**
	 * Deletes Entry by _ID
	 */
	public boolean deleteDbEntry(long rowId) {
		return database.delete(TABLE_NAME, _ID + "=" + rowId, null) > 0;
	}
	
	/**
	 * Return a Cursor over the list of all entries in the database
	 * 
	 * @return Cursor over all notes
	 */
	public Cursor fetchAllEntrys() {
		return database.query(TABLE_NAME, FROM, null, null, null,
				null, null);
	}
	
	/**
	 * Return a Cursor positioned at the defined entry by _ID
	 */
	public Cursor fetchEntry(long rowId) throws SQLException {
		Cursor mCursor = database.query(true, TABLE_NAME, FROM,
				_ID + "=" + rowId, null, null, null, null, null);
		if (mCursor != null) {
			mCursor.moveToFirst();
		}
		return mCursor;
	}
	
	private ContentValues createContentValues(String date, String time, String name) {
		//TODO edit this
		//http://www.vogella.de/articles/AndroidSQLite/article.html#todo_database
		ContentValues values = new ContentValues();
		values.put(DATE, date);
		values.put(TIME, time);
		values.put(NAME, name);
		return values;
	}
}